package com.hx.thread.cas;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Minghua Chen
 * @date 2020-09-06 15:16
 */
public class DebugCAS implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(DebugCAS.class);
    // 保证内存可见性
    private volatile int value;

    public synchronized int compareAndSet(int expectValue, int newValue) {
        int oldValue = value;
        if (oldValue == expectValue) {
            value = newValue;
            logger.info("执行成功");
        }
        return oldValue;
    }

    public static void main(String[] args) throws InterruptedException {
        DebugCAS instance = new DebugCAS();
        // 设置oldValue为100
        instance.value = 100;
        Thread t1 = new Thread(instance, "t1");
        Thread t2 = new Thread(instance, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        logger.info("" + instance.value);
    }

    @Override
    public void run() {
        compareAndSet(100, 150);
    }
}
